import * as http from 'http'
const platform = require("tns-core-modules/platform")
require( "nativescript-localstorage" )
const HOST = `https://7exdevapp.azurewebsites.net/api`
const HOST_TEST = localStorage.getItem('7HOST')

export function post(option) {
  console.log("net request: " + option.api);
  const token = localStorage.getItem('token')
  let headers = {
    "Content-Type": "application/json"
  }
  if (token) {
    headers["Authorization"] = `Bearer ${token}`
  }
  http.request({
    url: formHost() + option.api,
    method: "POST",
    headers,
    content: JSON.stringify(option.data)
  }).then((response) => {
    processResult(option, response)
  }, (error) => {
    console.log(error)
    option.error && option.error(500, 'Network error, try later')
  });
}

function formHost() {
  let host = HOST_TEST? HOST_TEST : HOST
  return `${host}/${platform.isIOS ? 'ios' : 'android'}/`
}

function processResult(option, response) {
  console.log(option.api + " response statusCode: " + response.statusCode)
  // console.log(response.content.toString())
  if (response.statusCode == 401) {
    let token = localStorage.getItem('token')
    localStorage.removeItem('token')
    option.error && option.error(401, token? 'Please login again' : 'Please login')
  } else if (response.statusCode != 200) {
    option.error && option.error(response.statusCode, 'Network error, try later')
  } else {
    let result = response.content.toJSON();
    if (result.code) {
      if (result.code == 200) {
        option.success && option.success(result.data)
      } else {
        option.error && option.error(result.code, result.msg)
      }
    } else {
      option.success && option.success(result)
    }
  }
}

export function get(option) {
  console.log("net request: " + option.api);
  const token = localStorage.getItem('token')
  let headers = undefined
  if (token) {
    headers = {
      "Authorization": `Bearer ${token}`
    }
  }
  http.request({
    url: formHost() + option.api,
    method: option.isDelete ? 'DELETE' : "GET",
    headers,
  }).then((response) => {
    processResult(option, response)
  }, (error) => {
    console.log(error)
    option.error && option.error(500, 'Network error, try later')
  });
}